<template>
  <div class="container mx-auto py-6 px-4">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">训练管理</h1>
      <p class="text-gray-600">管理和监控模型训练进程</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- 模型训练卡片 -->
      <div v-for="task in trainingTasks" :key="task.id" class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-semibold">{{ task.name }}</h2>
          <span :class="getStatusClass(task.status)">{{ task.status }}</span>
        </div>
        <div class="space-y-4">
          <div>
            <p class="text-sm text-gray-500">训练进度</p>
            <div class="w-full bg-gray-200 rounded-full h-2.5 mt-1">
              <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: `${task.progress}%` }"></div>
            </div>
            <p class="text-xs text-gray-500 mt-1">{{ task.progress }}% 完成</p>
          </div>
          <div>
            <p class="text-sm text-gray-500">准确率</p>
            <p class="text-lg font-medium">{{ task.accuracy }}%</p>
          </div>
          <div>
            <p class="text-sm text-gray-500">训练时间</p>
            <p class="text-lg font-medium">{{ formatTrainingTime(task.trainingTime) }}</p>
          </div>
          <div class="flex space-x-2">
            <button @click="viewTaskDetails(task)" class="px-3 py-1 bg-blue-50 text-blue-700 rounded-md text-sm hover:bg-blue-100">查看详情</button>
            <button v-if="task.status === '进行中'" @click="stopTraining(task)" class="px-3 py-1 bg-red-50 text-red-700 rounded-md text-sm hover:bg-red-100">停止训练</button>
            <button v-if="task.status === '暂停'" @click="resumeTraining(task)" class="px-3 py-1 bg-green-50 text-green-700 rounded-md text-sm hover:bg-green-100">继续训练</button>
          </div>
        </div>
      </div>

      <!-- 新建训练卡片 -->
      <div @click="showNewTrainingForm = true" class="bg-white rounded-lg shadow-md p-6 border-2 border-dashed border-gray-300 flex flex-col items-center justify-center cursor-pointer hover:bg-gray-50">
        <svg class="w-12 h-12 text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
        </svg>
        <p class="text-gray-600 font-medium">创建新训练任务</p>
        <p class="text-gray-400 text-sm mt-1">配置并启动新的模型训练</p>
      </div>
    </div>

    <!-- 新建训练表单 -->
    <div v-if="showNewTrainingForm" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-center justify-center">
      <div class="bg-white p-8 rounded-lg shadow-xl w-full max-w-md">
        <h2 class="text-2xl font-bold mb-4">创建新训练任务</h2>
        <form @submit.prevent="startNewTraining">
          <div class="mb-4">
            <label for="modelType" class="block text-sm font-medium text-gray-700">模型类型</label>
            <select v-model="newTraining.modelType" id="modelType" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
              <option value="lstm">LSTM</option>
              <option value="gru">GRU</option>
              <option value="transformer">Transformer</option>
            </select>
          </div>
          <div class="mb-4">
            <label for="stockCodes" class="block text-sm font-medium text-gray-700">股票代码 (逗号分隔)</label>
            <input v-model="newTraining.stockCodes" type="text" id="stockCodes" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
          </div>
          <div class="mb-4">
            <label for="epochs" class="block text-sm font-medium text-gray-700">训练轮数</label>
            <input v-model.number="newTraining.epochs" type="number" id="epochs" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
          </div>
          <div class="flex justify-end space-x-2">
            <button @click="showNewTrainingForm = false" type="button" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">取消</button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">开始训练</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core';

const trainingTasks = ref([]);
const showNewTrainingForm = ref(false);
const newTraining = ref({
  modelType: 'lstm',
  stockCodes: '',
  epochs: 100
});

onMounted(async () => {
  await fetchTrainingTasks();
});

async function fetchTrainingTasks() {
  try {
    const tasks = await invoke('get_training_tasks');
    trainingTasks.value = tasks;
  } catch (error) {
    console.error('Failed to fetch training tasks:', error);
  }
}

async function startNewTraining() {
  try {
    const result = await invoke('handle_unified_prediction', {
      request: {
        action: 'train',
        params: {
          model_type: newTraining.value.modelType,
          stock_codes: newTraining.value.stockCodes.split(',').map(code => code.trim()),
          epochs: newTraining.value.epochs
        }
      }
    });
    
    if (result.status === 'success') {
      console.log('Training started successfully:', result.data);
      showNewTrainingForm.value = false;
      await fetchTrainingTasks();
    } else {
      console.error('Failed to start training:', result.message);
    }
  } catch (error) {
    console.error('Error starting new training:', error);
  }
}

function getStatusClass(status) {
  switch (status) {
    case '进行中':
      return 'px-2 py-1 bg-green-100 text-green-800 text-xs font-medium rounded-full';
    case '暂停':
      return 'px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded-full';
    case '完成':
      return 'px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full';
    default:
      return 'px-2 py-1 bg-gray-100 text-gray-800 text-xs font-medium rounded-full';
  }
}

function formatTrainingTime(minutes) {
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}小时 ${remainingMinutes}分钟`;
}

async function viewTaskDetails(task) {
  console.log('View details for task:', task);
  // 实现查看任务详情的逻辑
}

async function stopTraining(task) {
  try {
    const result = await invoke('handle_unified_prediction', {
      request: {
        action: 'stop_training',
        params: { task_id: task.id }
      }
    });
    
    if (result.status === 'success') {
      console.log('Training stopped successfully:', result.data);
      await fetchTrainingTasks();
    } else {
      console.error('Failed to stop training:', result.message);
    }
  } catch (error) {
    console.error('Error stopping training:', error);
  }
}

async function resumeTraining(task) {
  try {
    const result = await invoke('handle_unified_prediction', {
      request: {
        action: 'resume_training',
        params: { task_id: task.id }
      }
    });
    
    if (result.status === 'success') {
      console.log('Training resumed successfully:', result.data);
      await fetchTrainingTasks();
    } else {
      console.error('Failed to resume training:', result.message);
    }
  } catch (error) {
    console.error('Error resuming training:', error);
  }
}
</script>